import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/widgets.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:xiandou/Common.dart';
import 'package:xiandou/Request/DioManager.dart';
import 'package:xiandou/Request/NWApi.dart';
import 'package:xiandou/Request/NWMethod.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:xiandou/home/TaskDetailView.dart';


class OrderListViewScreen extends StatefulWidget {
  int categoryId = 100;
  OrderListViewScreen({Key key, @required this.categoryId})
      : super(key:key);
  @override
  State<StatefulWidget> createState() =>  OrderListViewScreenState();
}

class OrderListViewScreenState extends State<OrderListViewScreen> {

  int _page = 1;
  EasyRefreshController _refreshController = EasyRefreshController();
  int _selectCategoryIndex =0;
  List categoryList = [{'name':'全部','state':'0'},{'name':'进行中','type':'1'},{'name':'审核中','type':'2'},{'name':'已完成','type':'3'},{'name':'审核失败','type':'4'}];
  List orderData = [];

  @override
  void initState() {
    super.initState();
    setState(() {
      _selectCategoryIndex =widget.categoryId;
    });
    print(categoryList[0].toString());
    requestRankingListData(categoryList[_selectCategoryIndex]['type'],true);
  }

  void requestRankingListData(String orderType,bool isRefresh) {
    var dic = {'state': orderType,'page':_page.toString()};
    DioManager().request(
        NWMethod.GET, NWApi.getOrderListDataApi, params: dic, success: (data) {
      print(data);
      setState(() {
        if(isRefresh){
          orderData = data;
        }else {
          orderData.addAll(data);
        }
      });
      Future.delayed(Duration(seconds: 1), (){
        setState(() {
          if(data.length > 19) {
            _refreshController.finishLoad(success: true, noMore: true);
            _refreshController.finishRefresh(success: true, noMore: true);
          }else {
            _refreshController.finishLoad(success: true, noMore: false);
            _refreshController.finishRefresh(success: true, noMore: false);
          }
        });
      });

    }, error: (error) {
      Fluttertoast.showToast(msg: error.message);
    });
  }

  Widget categotyWidget(String label, int index) {
    return new GestureDetector(
        onTap: () {
          _selectCategoryIndex = index;
          _page = 1;
          setState(() {
            requestRankingListData(categoryList[index]['type'],true);
          });
        },
        child: Container(
          width: MediaQuery.of(context).size.width / 5,
          child: Column(
            children: <Widget>[
              Expanded(
                  child: Padding(
                    padding: const EdgeInsets.only(top: 8),
                    child: Text(label, style: TextStyle(
                        fontSize: 14, color: Common.blackColor)),
                  )
              ),
              Offstage(
                  offstage: _selectCategoryIndex == index ? false : true,
                  child: Container(
                    height: 2,
                    width: 27.5,
                    margin: const EdgeInsets.only(bottom: 8),
                    decoration: new BoxDecoration(
                      color: Color(0xffFF5236),
                    ),
                  )
              )
            ],
          ),
        )
    );
  }

  Widget taskStatusLabel(int status) {
    if(status ==0){
      return Text('进行中',style: TextStyle(fontWeight: FontWeight.normal,fontSize: 14,color: Color(0xff00B838)),);
    }else if(status == 1) {
      return Text('审核中',style: TextStyle(fontWeight: FontWeight.normal,fontSize: 14,color: Color(0xffFF6528)),);
    }else if(status == 2) {
      return Text('已完成',style: TextStyle(fontWeight: FontWeight.normal,fontSize: 14,color: Common.grayColor),);
    }else if(status == -1) {
      return Text('任务失败',style: TextStyle(fontWeight: FontWeight.normal,fontSize: 14,color: Color(0xffFF1D1D)),);
    }else {
      return Text('------',style: TextStyle(fontWeight: FontWeight.normal,fontSize: 14,color: Common.grayColor),);
    }
  }

  Future<Null> _refresh() async {
    _page = 1;
    orderData.clear();
    requestRankingListData(categoryList[_selectCategoryIndex]['type'],true);
    return;
  }

  Future<dynamic> _onLoadmore() {
    _page++;
    requestRankingListData(categoryList[0]['type'],false);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CupertinoNavigationBar(
        backgroundColor: Colors.white,
        middle: const Text('全部任务'),
      ),
      body: Container(
        decoration: new BoxDecoration(
          color: Color(0xffF8F8F8),
        ),
        child: Column(
          children: <Widget>[
            Container(
              height: 44,
              child: ListView.builder(
                scrollDirection: Axis.horizontal,
                itemCount: categoryList.length,
                itemBuilder:(BuildContext context, int index) =>categotyWidget(categoryList[index]['name'], index),
              ),
            ),
            Expanded(
              child: EasyRefresh(
                child: ListView.builder(itemBuilder: (BuildContext context,int index){
                  if(orderData.length == 0) {
                    return Container(
                      padding: const EdgeInsets.only(top: 50),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Image(image: AssetImage('assets/d_empty.png'),width: 200,height: 200,),
                          SizedBox(height: 30,),
                          Text('暂无内容',style: TextStyle(color: Common.darkColor,fontSize: 14),),
                        ],
                      ),
                    );
                  }
                  return GestureDetector(
                    onTap: () {
                      var selectedTaskId = orderData[index]['taskId'];
                      Navigator.push(
                        context,
                        new MaterialPageRoute(builder: (context) => new TaskDetailPage(taskId:selectedTaskId)),
                      );
                    },
                    child: Container(
                      margin: const EdgeInsets.fromLTRB(10, 5, 10, 5),
                      decoration: new BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.all(Radius.circular(5.0)),
                      ),
                      height: 85,
                      child: Row(
                        children: <Widget>[
                          Expanded(
                              child:Padding(
                                  padding: const EdgeInsets.only(left: 20,top: 20,bottom: 20),
                                  child: Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                                    children: <Widget>[
                                      Text(orderData[index]['taskTitle'],style: TextStyle(fontWeight: FontWeight.bold,fontSize: 16,color: Common.blackColor),),
                                      Padding(
                                        padding: const EdgeInsets.only(top: 5),
                                        child: Text(orderData[index]['createTime'],style: TextStyle(fontSize: 13,color: Common.darkColor),),
                                      )
                                    ],
                                  )
                              )
                          ),
                          Padding(
                              padding: const EdgeInsets.only(right: 20,top: 15,bottom: 15),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.end,
                                mainAxisAlignment: MainAxisAlignment.spaceAround,
                                children: <Widget>[
                                  taskStatusLabel(orderData[index]['taskStatus']),
                                  Row(
                                    children: <Widget>[
                                      new Image.asset('assets/xiandou.png',width: 16,height: 16,),
                                      SizedBox(width: 5,),
                                      Text(orderData[index]['award'].toString(),style: (TextStyle(color: Color(0xffFFBD18),fontWeight: FontWeight.bold,fontSize: 17)),)
                                    ],
                                  ),
                                ],
                              )
                          )
                        ],
                      ),
                    )
                  );
                },itemCount: orderData.length == 0 ? 1 : orderData.length,),
                onRefresh: () async{
                  _refresh();
                },
                onLoad: () async{
                  _onLoadmore();
                },
                bottomBouncing: true,
                enableControlFinishRefresh: false,
                enableControlFinishLoad: false,
              )
            )
          ],
        ),
      ),
    );
    // TODO: implement build
    throw UnimplementedError();
  }
}